import { reactive, ref } from 'vue';
import axios from '@/config/axios/index.ts';
import { VxeUI } from 'vxe-pc-ui';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { VxeGridInstance, VxeGridProps } from 'vxe-table';
import type {
	CommonFileUpDownLoadProps
} from '#/src/components/customComponents/fileUpLoad/modal/ModalFileUpLoadListProps.d.ts';
const useGridHooks = (props: CommonFileUpDownLoadProps) => {
	//---------------------------------------------------表格类-----------------------------------------------------------
	const gridConfig = reactive<VxeGridProps>({
		loading       : false,
		height        : '500',
		align         : 'center',
		pagerConfig   : {
			currentPage : 1,
			pageSize    : 20,
			total       : 0
		},
		toolbarConfig : {
			size : 'small'
		},
		formConfig    : {
			enabled : false,
			data    : {}
		},
		columns       : [
			{
				field        : 'fileName',
				title        : '文件名',
				showOverflow : 'tooltip'
			},
			{
				field        : 'fileSize',
				title        : '文件大小',
				showOverflow : 'tooltip'
			},
			{
				field        : 'createTime',
				title        : '上传时间',
				showOverflow : 'tooltip'
			},
			{
				title        : '操作',
				showOverflow : 'tooltip',
				slots        : {
					// 使用 JSX 渲染
					default : 'operate'
				}
			}
		],
		data          : []
	});
	// 已上传文件列表
	const uploadFileGridRef = ref<VxeGridInstance>();
	/**
	 * 初始化表格数据
	 */
	const initGrid = async (): Promise<void> => {
		// 将表格的 loading 属性设置为 true,进入加载状态
		gridConfig.loading = true;
		// 清空当前选择行和选择列
		uploadFileGridRef.value?.clearCurrentRow();
		uploadFileGridRef.value?.clearCurrentColumn();
		// 将表单数据设置为搜索条件对象
		gridConfig.formConfig!.data = {
			...gridConfig.formConfig!.data,
			...props.fileQuery.params,
			// 设置页码和每页个数
			pageNum  : gridConfig.pagerConfig!.currentPage,
			pageSize : gridConfig.pagerConfig!.pageSize
		};
		axios<any, JsonResultProps<any>, any>({
			method : 'POST',
			url    : props.fileQuery.url,
			data   : gridConfig.formConfig!.data
		}).then((jsonResult: JsonResultProps<any>) => {
			// 如果返回的状态为true，则将结果数据赋值给表格数据，并将 loading 属性设置为false
			if (jsonResult.status) {
				// 将总记录数赋值给表格的总记录数
				gridConfig.pagerConfig!.total = jsonResult.data.total;
				// 将结果数据赋值给表格的数据
				gridConfig.data = jsonResult.data.records;
				// 将 loading 属性设置为false
				gridConfig.loading = false;
			} else {
				// 使用 VXETable 提供的 modal.message 函数显示警告消息
				VxeUI.modal.message({ content : jsonResult.msg, status : 'warning', id : 'failedMessage' });
				// 将 loading 属性设置为false
				gridConfig.loading = false;
			}
		}).catch(error => {
			// 如果出现了错误，则将错误信息打印到控制台，并使用 VXETable 提供的 modal.message 函数显示错误消息
			console.error(error);
			VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
			// 将 loading 属性设置为false
			gridConfig.loading = false;
		});
	};
	const changePage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }): Promise<void> => {
		gridConfig.pagerConfig!.currentPage = currentPage;
		gridConfig.pagerConfig!.pageSize = pageSize;
		await initGrid();
	};
	const queryCondition = async (): Promise<void> => {
		await initGrid();
	};
	const download = async (rowData: any): Promise<void> => {
		const data: Record<string, any> = props.fileQuery.downLoad.params;
		// AI:帮我遍历props.fileQuery.downLoad.fieldMap中的内容
		for (const key in props.fileQuery.downLoad.fieldMap) {
			if (Object.prototype.hasOwnProperty.call(props.fileQuery.downLoad.fieldMap, key)) {
				data[key] = rowData[key];
			}
		}
		axios<any, BlobPart, any>({
			method       : 'POST',
			url          : props.fileQuery.downLoad.url,
			data         : data,
			responseType : 'blob'
		}).then((jsonResult: BlobPart) => {
			console.log(jsonResult);
			// @ts-ignore
			if ('application/octet-stream' !== jsonResult.type) {
				// 如果返回的不是下载流,那么就转换成JSON对象
				// @ts-ignore
				jsonResult.text().then((result: any) => {
					// 解析 JSON 字符串,并提示用户
					const jsonObj = JSON.parse(result);
					VxeUI.modal.message({
						content : jsonObj?.msg,
						status  : 'warning',
						id      : 'warningMessage'
					});
				});
				// 终止执行
				return;
			}
			// 处理文档流
			// @ts-ignore
			const blob: Blob = new Blob([jsonResult]);
			const eLink: HTMLAnchorElement = document.createElement('a');
			eLink.download = rowData.fileName;
			eLink.style.display = 'none';
			// @ts-ignore
			eLink['href'] = URL.createObjectURL(blob);
			document.body.appendChild(eLink);
			eLink.click();
			// 释放URL对象
			URL.revokeObjectURL(eLink.href);
			document.body.removeChild(eLink);
		}).catch(errorObj => {
			console.error(errorObj);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
		});
	};
	const remove = async (rowData: any): Promise<void> => {
		VxeUI.modal.confirm({
			content : '您确定要删除该文件吗?',
			title   : '确认删除',
			id      : 'deleteModalUnique'
		}).then((type: any) => {
			if ('confirm' === type) {
				const data: Record<string, any> = props.fileQuery.remove.params;
				// AI:帮我遍历props.fileQuery.remove.fieldMap中的内容
				for (const key in props.fileQuery.remove.fieldMap) {
					if (Object.prototype.hasOwnProperty.call(props.fileQuery.remove.fieldMap, key)) {
						data[key] = rowData[key];
					}
				}
				axios<any, JsonResultProps<any>, any>({
					method : 'DELETE',
					url    : props.fileQuery.remove.url,
					data   : data
				}).then((jsonResult: JsonResultProps<any>) => {
					if (jsonResult.status) {
						VxeUI.modal.message({
							content : jsonResult.msg,
							status  : 'success',
							id      : 'successMessage'
						});
					} else {
						VxeUI.modal.message({
							content : jsonResult.msg,
							status  : 'warning',
							id      : 'failedMessage'
						});
					}
					initGrid();
				}).catch(errorObj => {
					console.error(errorObj);
					VxeUI.modal.message({
						content : '系统异常,请稍后再试',
						status  : 'error',
						id      : 'errorMessage'
					});
				});
			}
		});
	};
	return {
		gridConfig,
		uploadFileGridRef,
		initGrid,
		changePage,
		queryCondition,
		download,
		remove
	};
};
export default useGridHooks;